<?php
// 详细查询订单57相关型号的工序物料配置和计算逻辑

// 数据库连接信息
$host = '127.0.0.1';
$dbname = 'scanwork';
$username = 'scanwork';
$password = 'rDezxK9h7tWp5sP7';
$port = 3306;

$orderId = 57; // 要查询的订单ID

try {
    // 创建数据库连接
    $pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "\n=== 订单57物料计算问题详细分析 ===\n\n";
    
    // 1. 查询订单57的所有型号
    echo "1. 查询订单57的所有型号...\n";
    $stmt = $pdo->prepare("SELECT * FROM fa_scanwork_order_model WHERE order_id = ?");
    $stmt->execute([$orderId]);
    $orderModels = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "找到" . count($orderModels) . "个型号\n\n";
    
    // 2. 对每个型号，详细查询其工序物料配置
    echo "2. 详细查询每个型号的工序物料配置...\n\n";
    
    $allProcessMaterials = [];
    $materialCountByModel = [];
    
    foreach ($orderModels as $model) {
        $modelId = $model['id'];
        $productModelId = null;
        
        // 找出型号ID字段
        foreach (array_keys($model) as $key) {
            if (stripos($key, 'model_id') !== false) {
                $productModelId = $model[$key];
                break;
            }
        }
        
        if (!$productModelId) {
            echo "型号ID: $modelId - 未找到产品型号ID字段\n";
            continue;
        }
        
        echo "型号ID: $modelId, 产品型号ID: $productModelId, 数量: {$model['quantity']}\n";
        
        // 查询该产品型号的所有工序物料配置
        $stmt2 = $pdo->prepare("SELECT pm.*, p.name as process_name, m.name as material_name 
                                FROM fa_scanwork_process_material pm
                                LEFT JOIN fa_scanwork_process p ON pm.process_id = p.id
                                LEFT JOIN fa_scanwork_material m ON pm.material_id = m.id
                                WHERE pm.model_id = ?");
        $stmt2->execute([$productModelId]);
        $processMaterials = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        
        $materialCountByModel[$modelId] = count($processMaterials);
        
        if (!empty($processMaterials)) {
            echo "  工序物料配置: (共" . count($processMaterials) . "条)\n";
            
            foreach ($processMaterials as $pm) {
                echo "    工序ID: {$pm['process_id']}, 工序: {$pm['process_name']}, ";
                echo "物料ID: {$pm['material_id']}, 物料: {$pm['material_name']}, ";
                echo "用量: {$pm['quantity']}, 损耗率: {$pm['loss_rate']}%\n";
                
                // 记录所有物料ID
                $materialId = $pm['material_id'];
                if (!isset($allProcessMaterials[$materialId])) {
                    $allProcessMaterials[$materialId] = [
                        'name' => $pm['material_name'],
                        'processes' => []
                    ];
                }
                $allProcessMaterials[$materialId]['processes'][] = [
                    'process_id' => $pm['process_id'],
                    'process_name' => $pm['process_name']
                ];
            }
        } else {
            echo "  无工序物料配置\n";
        }
        echo "\n";
    }
    
    // 3. 统计所有物料及其涉及的工序
    echo "3. 所有物料及其涉及的工序统计：\n";
    echo "总共有" . count($allProcessMaterials) . "种物料\n";
    foreach ($allProcessMaterials as $materialId => $data) {
        echo "物料ID: $materialId, 物料: {$data['name']}, 涉及工序数: " . count($data['processes']) . "\n";
        foreach ($data['processes'] as $process) {
            echo "  - 工序ID: {$process['process_id']}, 工序: {$process['process_name']}\n";
        }
    }
    echo "\n";
    
    // 4. 查询订单57的物料需求记录
    echo "4. 查询订单57的物料需求记录：\n";
    $stmt3 = $pdo->prepare("SELECT om.*, m.name as material_name
                            FROM fa_scanwork_order_material om
                            LEFT JOIN fa_scanwork_material m ON om.material_id = m.id
                            WHERE om.order_id = ?");
    $stmt3->execute([$orderId]);
    $orderMaterials = $stmt3->fetchAll(PDO::FETCH_ASSOC);
    
    echo "找到" . count($orderMaterials) . "条订单物料需求记录\n";
    if (!empty($orderMaterials)) {
        foreach ($orderMaterials as $om) {
            echo "物料ID: {$om['material_id']}, 物料: {$om['material_name']}, ";
            echo "需求数量: {$om['required_quantity']}, ";
            echo "供应商ID: {$om['supplier_id']}, ";
            echo "损耗率: {$om['loss_rate']}%\n";
            
            // 检查是否缺少工序相关信息
            echo "  缺少工序信息: " . (isset($om['process_id']) ? "否" : "是") . "\n";
        }
    }
    
    // 5. 分析calculateMaterialsWithCost方法的逻辑问题
    echo "\n5. 问题分析：\n";
    echo "根据查询结果和代码分析，发现calculateMaterialsWithCost方法存在以下问题：\n";
    echo "- 该方法使用material_id作为数组键来合并不同工序的同一物料\n";
    echo "- 没有将process_id保存到订单物料需求记录中\n";
    echo "- 当多个工序使用相同物料时，它们会被合并成一条记录\n";
    echo "- 这就解释了为什么订单57有多个工序物料配置但只生成了" . count($orderMaterials) . "条记录\n";
    
    echo "\n=== 分析完成 ===\n";
    
} catch (PDOException $e) {
    echo "数据库连接或查询失败：" . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "查询出错：" . $e->getMessage() . "\n";
}